//
//  CSGXCommInfoView.m
//

#import "CSGXCommInfoView.h"
#import "LKGXDropDownListButton.h"
#import "LKGXNumberModificationView.h"
#import "CSTextField.h"

#import "TCommodityInfoDAL.h"

#import "TOrderInfoModel.h"

#import "CSGXCommodityPickerBLL.h"

@interface CSGXCommInfoView () <UIGestureRecognizerDelegate, NumberModificationViewDelegate>

#pragma mark controls
@property (nonatomic, strong) UILabel * lblHeader; // 商品名称
@property (nonatomic, strong) LKGXDropDownListButton * btnSaleType; // 选取商品类型按钮
@property (nonatomic, strong) UILabel * lblInventory; //显示库存信息
@property (nonatomic, strong) NSArray<LKGXNumberModificationView *> * vCountModificationArr; //商品数量修改view
@property (nonatomic, strong) UILabel * lblPriceType; //价格类型（标准价）
@property (nonatomic, strong) UIView * vPrice; //单价view（包含‘单价文本框’ 和 ‘单位选择按钮’）
@property (nonatomic, strong) CSTextField * txtPrice; //单价文本框
@property (nonatomic, strong) LKGXDropDownListButton * btnPriceUnit; //单价单位
@property (nonatomic, strong) CSTextField * txtTotalPrice; //当前商品总件数的总金额文本框
@property (nonatomic, strong) CSTextField * txtTime; //日期
@property (nonatomic, strong) CSBaseTextField * txtRemark; //备注
@property (nonatomic, strong) UIButton * btnRemarkScan; //备注后面的扫码按钮

#pragma mark checkView
@property (nonatomic, weak) UIView *vCheck;
@property (nonatomic, weak) UITextView *tvwRemark;
///盘平、盘零、未盘
@property (nonatomic, strong) NSMutableArray<UIButton *> *btnCheckList;

//@property (nonatomic, strong) TInventoryModel *originInventoryModel;



#pragma mark data
/// 产品档案model
@property (nonatomic, strong) TCommodityInfoModel * commInfoModel;
/// unitArr 与单位相对应的价格数组
@property (nonatomic, copy) NSArray * priceArr;
/// unitConversionArr 与单位对应的 单位换算（*50,*10,*1）
@property (nonatomic, strong) NSArray * unitConversionArr;

/// 预览订单model
@property (nonatomic, strong) NSArray<TOrderInfoModel *> * previewOrderModel;


/// 从所有'数量修改view' 中回调回来的换算成最小单位的总数量。
@property(nonatomic, assign) int totalCount;
/// 从数量修改view 中回调的tag，确定单位。
@property(nonatomic, assign) NSInteger currentCountModiTag;

/// 上一个tvThirdCell索引
@property(nonatomic, assign) NSInteger lastSelectedThirdIndex;
/// 上一个tvPreviewCell索引
@property(nonatomic, assign) NSInteger lastSelectedPreviewIndex;
/// 是编辑还是生成新的（修改不同的单位属于编辑，前提是从同一个cellIndex上过来）
@property(nonatomic, assign) BOOL isEdit;


@end

@implementation CSGXCommInfoView

+ (instancetype)commInfoViewWithControllerEnum:(ViewControllerEnum)controllerEnum {
    id obj = [[self alloc] init];
    ((CSGXCommInfoView *)obj).viewControllerEnum = controllerEnum;
    [((CSGXCommInfoView *)obj) initUI];
    return obj;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initData {
    self.isPreview = NO;
    //    self.orderFlag = NO;
    self.selectedThirdIndex = -1;
    self.selectedPreviewIndex = -1;
    
    self.lastSelectedThirdIndex = -1;
    self.lastSelectedPreviewIndex = -1;
}

#pragma mark - Actions
- (void)didEdit:(NSNotification *)note {
    if ([self.tvwRemark.text isEqualToString:@"产品备注"]) {
        self.tvwRemark.text = @"";
    }
}

///3个按钮的点击事件
- (void)btnCheckClick:(UIButton *)sender {
    //    NSLog(@"%@", @(sender.tag).description);
    if (self.selectedThirdIndex == -1 && self.selectedPreviewIndex == -1) {
        
        [CSGXProgressTool showErrorWithStatus:@"请先选择商品！" delay:0.3];
        NSLog(@"Msg: 请先选择商品！");
        [self clearInfo_check];
        return;
    }
    
    BOOL isNotChecked = NO;
    switch (sender.tag) {
        case 0:
            [self checkOrigin]; //盘平
            break;
        case 1:
            [self checkZero]; //盘零
            break;
        case 2:
            [self checkNone]; //未盘
            isNotChecked = YES;
            break;
            
        default:
            break;
    }
#pragma mark back call
    if (self.callbackWithInventoryModel) {
        self.callbackWithInventoryModel(self.inventoryModel, isNotChecked);
    }
    
    NSArray *countArr = [self.inventoryModel.iInventoryCount componentsSeparatedByString:@","];
    for (int i = 0; i < self.numberModificationCount; i++) {
        if (isNotChecked) {
            self.vCountModificationArr[i].commodityCount = 0;
        }else {
            self.vCountModificationArr[i].commodityCount = [countArr[i] intValue];
        }
    }
}

#pragma mark - methods
- (void)checkZero {
    NSLog(@"盘零");
    self.inventoryModel.iInventoryCount = [CSGXCommodityPickerBLL modifyCountWithCountStr:self.inventoryModel.iInventoryCount
                                                                                    index:-1
                                                                                    count:0];
    self.inventoryModel.iIsChecked = 2;
    self.inventoryModel.iCheckedTime = [CSGXDateFormatterManager sharedManager].currentDay;
}

- (void)checkOrigin {
    NSLog(@"盘平");
    self.inventoryModel = [CSGXCommodityPickerBLL loadInventoryModelWithCommNo:self.inventoryModel.iCoNo];
    self.inventoryModel.iIsChecked = 3;
    self.inventoryModel.iCheckedTime = [CSGXDateFormatterManager sharedManager].currentDay;
}

- (void)checkNone {
    NSLog(@"未盘");
    self.inventoryModel = [CSGXCommodityPickerBLL loadInventoryModelWithCommNo:self.inventoryModel.iCoNo];
    self.inventoryModel.iIsChecked = 0;
}


- (NSArray<NSString *> *)getAppendedArr:(NSArray<NSString *> *)originArr appendStr:(NSString *)appendStr {
    //
    NSMutableArray<NSString *> * mArr = [NSMutableArray<NSString *> array];
    for (NSString *str in originArr) {
        [mArr addObject:[appendStr stringByAppendingString:str]];
    }
    return mArr.copy;
}

- (void)clearInfo_check {
    self.lblHeader.text = @"";//
    self.txtTime.text = @"";
    self.lblInventory.text = @"参考：**箱";
    for (int i = 0; i < self.numberModificationCount; i++) {
        self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": @"箱"};
    }
    
    _tvwRemark.text = @"产品备注";
    _tvwRemark.textColor = [UIColor grayColor];
    _tvwRemark.layer.borderColor = [UIColor grayColor].CGColor;
    _tvwRemark.layer.borderWidth = 2;
    _tvwRemark.layer.shadowOpacity = 0.5;
    _tvwRemark.layer.shadowOffset = CGSizeMake(3, 3);
    
    [self initData];
}

- (void)clearDetailInfo {
    self.lblHeader.text = @"";//
    self.lblInventory.text = @"库存：**箱";
    for (int i = 0; i < self.numberModificationCount; i++) {
        self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": @"箱"};
    }
    self.lblPriceType.text = @"";
    self.txtPrice.text = @"";
    self.txtTotalPrice.text = @"";
    self.txtTime.text = @"";
    self.txtRemark.text = @"";
    
    [self initData];
}

/// load commInfoModel with category
- (TCommodityInfoModel *)loadCommInfoModelWithCategory:(NSString *)commodityCategory {
    return [TCommodityInfoDAL loadModelWithCategory:commodityCategory];
}

/// load commInfoModel with commNo
- (TCommodityInfoModel *)loadCommInfoModelWithCommNo:(NSString *)commNo {
    return [TCommodityInfoDAL loadModelWithCommNo:commNo];
}

/// createLKGXNumberModificationViews
- (NSInteger)createNumberModificationViews {
    NSMutableArray<LKGXNumberModificationView *> * nmViewArr = [NSMutableArray array];
    if (self.numberModificationCount == 0) {
        return 0;
    }
    
    // 移除之前的，重新根据model创建
    for (int i = 0; i < self.vCountModificationArr.count; i++) {
        [self.vCountModificationArr[i] removeFromSuperview];
    }
    
    for (int i = 0; i < self.numberModificationCount; i++) {
        LKGXNumberModificationView * nmView = [LKGXNumberModificationView modificationView];
        [self addSubview:nmView];
        
        nmView.tag = i;
        nmView.countDelegate = self;
        
        [nmViewArr addObject:nmView];
    }
    
    CGFloat margin_unit_type = 10; //布局时用到的控件之间的间距
    
    if (self.numberModificationCount > 0) {
        //
        [nmViewArr[0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lblInventory.mas_bottom).mas_offset(margin_unit_type*1/3);
            make.leading.trailing.equalTo(self);
        }];
        
        if (self.numberModificationCount == 2) {
            //
            [nmViewArr[1] mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(nmViewArr[0].mas_bottom).mas_offset(margin_unit_type);
                make.leading.trailing.equalTo(self);
            }];
        }else if (self.numberModificationCount > 2) {
            //
            for (int i = 1; i < nmViewArr.count - 1; i++) {
                
                [nmViewArr[i] mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(nmViewArr[i-1].mas_bottom).mas_offset(margin_unit_type);
                    make.leading.trailing.equalTo(self);
                }];
            }
            
            [[nmViewArr lastObject] mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(nmViewArr[nmViewArr.count - 2].mas_bottom).mas_offset(margin_unit_type);
                make.leading.trailing.equalTo(self);
            }];
        }
    } // nmViewCount > 0    end
    self.vCountModificationArr = nmViewArr.copy;
    return self.numberModificationCount;
}

- (NSArray *)getUnitConversionArrWithUnitConversionStr:(NSString *)unitConversionStr {
    NSArray * arr =  [unitConversionStr componentsSeparatedByString:@","];
    
    NSMutableArray * mArr = [NSMutableArray array];
    for (NSString * str in arr) {
        NSString * temp = [str substringFromIndex:1];
        [mArr addObject:temp];
    }
    return mArr.copy;
}

/// 生成新的saleInfoModel，数据来源于控件。
- (TSaleInfoModel *)createSaleModel {
    //
    TSaleInfoModel * saleModel = [[TSaleInfoModel alloc] init];
    
    NSString * sOrderNo = @"";
    NSString * sCoNo = @"";
    NSString * sName = @"";
    NSString * sCategory = @"";
    NSString * sUnit = @"";
    NSString * sPrice = @"";
    NSString * sCount = @"";
    //    NSString * sUnitMoney = @"";
    //    CGFloat sTotalMoney = 0;
    NSString * sWarehouseNo = @"";
    NSString * sWarehouseName = @"";
    NSString * sSalesmanNo = @"";
    NSString * sSalesman = @"";
    NSString * sBusinessmanNo = @"";
    NSString * sBusinessman = @"";
    int sSaleType = 0;
    int sSettlementType = 0;
    int sPromotionType = 0;
    int sState = 0;
    NSString * sRemark = @"";
    
    //
    sCoNo = self.commInfoModel.cCoNo;
    sName = self.commInfoModel.cName;
    sCategory = self.commInfoModel.cCategory;
    sUnit = self.commInfoModel.cUnit;
    sPrice = self.commInfoModel.cPrice;
    
    for (int i = 0; i < self.vCountModificationArr.count; i++) {
        sCount = [sCount stringByAppendingFormat:@"%d,", self.vCountModificationArr[i].commodityCount];
    }
    sCount = [sCount substringToIndex:sCount.length-1];
    sWarehouseNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"warehouseNo"];
    sWarehouseName = [[NSUserDefaults standardUserDefaults] objectForKey:@"warehouseName"];;
    sSalesmanNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"userNo"];;
    sSalesman = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];;
    sBusinessmanNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"businessNo"];;
    sBusinessman = [[NSUserDefaults standardUserDefaults] objectForKey:@"businessName"];;
    sSaleType = 0;
    sSettlementType = 0;
    sPromotionType = 0;
    sState = 0;
    sRemark = self.txtRemark.text;
    
    //    saleModel.sName = sId
    saleModel.sOrderNo = sOrderNo;
    saleModel.sCoNo = sCoNo;
    saleModel.sName = sName;
    saleModel.sCategory = sCategory;
    saleModel.sUnit = sUnit;
    saleModel.sPrice = sPrice;
    saleModel.sCount = sCount;
    saleModel.sWarehouseNo = sWarehouseNo;
    saleModel.sWarehouseName = sWarehouseName;
    saleModel.sSalesmanNo = sSalesmanNo;
    saleModel.sSalesman = sSalesman;
    saleModel.sBusinessmanNo = sBusinessmanNo;
    saleModel.sBusinessman = sBusinessman;
    saleModel.sSaleType = sSaleType;
    saleModel.sSettlementType = sSettlementType;
    saleModel.sPromotionType = sPromotionType;
    saleModel.sCreateTime = [[CSGXDateFormatterManager sharedManager] currentTime];
    saleModel.sState = sState;
    saleModel.sRemark = sRemark;
    
    return saleModel;
}

/// 更新传进来的saleModel
- (void)updateSaleModel:(TSaleInfoModel *)originSaleModel {
    
    originSaleModel.sCount = [NSString stringWithFormat:@"%d", self.totalCount]; //test
    
}
#pragma mark distribute
- (void)distributeWithInventoryModel:(TInventoryModel *)inventoryModel {
    //
    NSArray *iUnitArr = [inventoryModel.iUnit componentsSeparatedByString:@","];
    NSArray *iCountArr = [inventoryModel.iInventoryCount componentsSeparatedByString:@","];
    NSString *inventoryStr = @"参考：";
    self.numberModificationCount = iCountArr.count;
    
    if (self.numberModificationCount > 0) {
        [self.vCheck mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.vCountModificationArr.lastObject.mas_bottom).mas_offset(7);
            make.leading.trailing.equalTo(self).mas_offset(0);
            make.height.mas_offset(30);
        }];
    }
    
    if (inventoryModel) {
        for (int i = 0; i < self.numberModificationCount; i++) {
            if (self.isPreview) {
                self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": iUnitArr[i], @"unitCount":iCountArr[i]};
            }else {
                self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": iUnitArr[i], @"unitCount": @""};
                inventoryModel.iInventoryCount = [CSGXCommodityPickerBLL modifyCountWithCountStr:inventoryModel.iInventoryCount index:-1 count:0];
            }
            //设置inventoryStr
            inventoryStr = [inventoryStr stringByAppendingFormat:@"%@%@", iCountArr[i], iUnitArr[i]];
        }
    }else {
        for (int i = 0; i < self.numberModificationCount; i++) {
            if (self.isPreview) {
                // 给 countModiView 设置数据
                self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": iUnitArr[i]};
            } else {
                // 给 countModiView 设置数据
                self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": iUnitArr[i]};
            }
        }
    }
    
    //
    self.lblHeader.text = inventoryModel.iName;
    self.txtTime.text = [CSGXDateFormatterManager sharedManager].currentDay;
    
    NSMutableAttributedString *mAttrInventory = [[NSMutableAttributedString alloc] initWithString:inventoryStr];
    [mAttrInventory setAttributes:@{NSForegroundColorAttributeName: kColorBar} range:NSMakeRange(0, 3)];
    self.lblInventory.attributedText = mAttrInventory;
    
}

/// 给 detailView（commInfoView）的内部控件分发数据 distribute
- (void)distributeWithCommInfoModel:(TCommodityInfoModel *)commInfoModel saleModel:(TSaleInfoModel *)saleModel {
    //
    NSArray * saleTypeArr = @[@"正常销售", @"赠品销售"];
    self.btnSaleType.textList = saleTypeArr;
    __block NSInteger saleTypeIndex = 0;
    self.btnSaleType.drapDownListCallbackBlock = ^(NSInteger index) {
#pragma mark call back
        //#warning 后续下单时处理 saleTypeIndex
        saleTypeIndex = index;
    };
    
    // unitArr
    NSArray * unitArr = [commInfoModel.cUnit componentsSeparatedByString:@","];
    
    self.numberModificationCount = unitArr.count;
    
    // unitCountArr
    NSArray * unitCountArr = [NSArray array];
    
    if (saleModel) {
        unitCountArr = [saleModel.sCount componentsSeparatedByString:@","];
        for (int i = 0; i < self.numberModificationCount; i++) {
            // 给 countModiView 设置数据
            self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": unitArr[i], @"unitCount":unitCountArr[i]};
        }
    }else {
        for (int i = 0; i < self.numberModificationCount; i++) {
            // 给 countModiView 设置数据
            self.vCountModificationArr[i].dataNumModiDict = @{@"unitType": unitArr[i]};
        }
    }
    
    // priceArr
    NSArray * priceArr = [commInfoModel.cPrice componentsSeparatedByString:@","];
    self.priceArr = priceArr;
    
    // unitConversionArr
    NSArray * unitConversionArr = [self getUnitConversionArrWithUnitConversionStr:commInfoModel.cUnitConversion];
    self.unitConversionArr = unitConversionArr;
    
    NSArray * priceUnitArr = [self getAppendedArr:unitArr appendStr:@"元/"];
    
    self.btnPriceUnit.textList = priceUnitArr;
    __weak typeof(self) weakSelf = self;
    self.btnPriceUnit.drapDownListCallbackBlock = ^(NSInteger index) {
#pragma mark call back -unit
        //单位类型回调
        weakSelf.txtPrice.text = priceArr[index];
    };
    
    self.lblHeader.text = commInfoModel.cName;//
    self.lblInventory.text = @"库存：**箱";
    self.lblPriceType.text = commInfoModel.cPriceType;
    self.txtPrice.text = priceArr[0];
    //    self.txtTotalPrice.text = @""; //计算总价
    self.txtTime.text = @"today";
    self.txtRemark.text = @"remark_origin";
    self.txtTotalPrice.text = [NSString stringWithFormat:@"%.2f", saleModel.sTotalMoney];
}

/// 计算总价
- (CGFloat)calculateUnitMoneyAndTotalMoney:(TSaleInfoModel *)saleModel {
    // 遍历 numberModificationViewArr ，分别取到count。
    //    int totalCount = 0;
    
    CGFloat totalMoneyF = 0;// 所有单位所有数量的总价
    NSString * unitMoneyStr = @"";
    for (int i = 0 ; i < self.vCountModificationArr.count; i++) {
        CGFloat unitMoney = self.vCountModificationArr[i].commodityCount * [self.priceArr[i] floatValue];
        unitMoneyStr = [unitMoneyStr stringByAppendingFormat:@"%.2f,", unitMoney];
        totalMoneyF += unitMoney;
    }
    
    unitMoneyStr = [unitMoneyStr subStringFrontOfLastIndex:1];
    
    saleModel.sUnitMoney = unitMoneyStr;
    saleModel.sTotalMoney = totalMoneyF;
    
    return totalMoneyF;
}

- (BOOL)getIsEdit {
    if (self.lastSelectedThirdIndex == self.selectedThirdIndex && self.selectedThirdIndex != -1) {
        return YES;
    }
    return NO;
}

#pragma mark - delegate 数量修改回调
- (void)numberModificationView:(LKGXNumberModificationView *)numberModificationView commodityCount:(NSInteger)commodityCount {
    
#pragma mark ViewControllerCarSale 车销销售
    if (self.viewControllerEnum == ViewControllerCarSale) {
        //
        self.currentCountModiTag = numberModificationView.tag; //修改的哪个单位的数量
        if (self.selectedThirdIndex == -1 && self.selectedPreviewIndex == -1) {
            
            [CSGXProgressTool showErrorWithStatus:@"请先选择商品！" delay:0.3];
            NSLog(@"Msg: 请先选择商品！");
            [self clearDetailInfo];
            return;
        }
        
        // 生成新saleModel
        TSaleInfoModel * saleInfoModel = [self createSaleModel];
        
        // 修改总价并显示
        CGFloat totalPriceF = [self calculateUnitMoneyAndTotalMoney:saleInfoModel];
        self.txtTotalPrice.text = [NSString stringWithFormat:@"%.2f", totalPriceF];
#pragma mark back call
        // 生成新saleModel之后，马上回传给commVc
        if (self.callbackWithSaleModel) {
            self.callbackWithSaleModel(saleInfoModel, self.isEdit, self.selectedPreviewIndex);
            self.isEdit = [self getIsEdit];
        }
    }
#pragma mark ViewControllerInventoryCheck 库存盘点
    else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
        //
        self.currentCountModiTag = numberModificationView.tag; //修改的哪个单位的数量
        if (self.selectedThirdIndex == -1 && self.selectedPreviewIndex == -1) {
            
            [CSGXProgressTool showErrorWithStatus:@"请先选择商品！" delay:0.3];
            NSLog(@"Msg: 请先选择商品！");
            [self clearInfo_check];
            return;
        }
        
        //修改库存数量
        NSString *inventoryCountS = [CSGXCommodityPickerBLL modifyCountWithCountStr:self.inventoryModel.iInventoryCount
                                                                                        index:self.currentCountModiTag
                                                                                        count:self.vCountModificationArr[self.currentCountModiTag].commodityCount];
        self.inventoryModel.iInventoryCount = inventoryCountS;
        
        InventoryCheckType checkType = [CSGXCommodityPickerBLL getInventoryTypeWithCountStr:inventoryCountS
                                                                                     commNo:self.inventoryModel.iCoNo];
        self.inventoryModel.iIsChecked = checkType;
        self.inventoryModel.iCheckedTime = [CSGXDateFormatterManager sharedManager].currentDay;
#pragma mark back call
        if (self.callbackWithInventoryModel) {
            self.callbackWithInventoryModel(self.inventoryModel, NO);
        }
    }
    
    
}


#pragma mark - setter & getter

- (void)setNumberModificationCount:(NSInteger)numberModificationCount {
    _numberModificationCount = numberModificationCount;
    
    // 创建 numberModificationView 并布局
    NSInteger count = [self createNumberModificationViews];
    if (count == 0) {
        return;
    }
    
    // 更新下一个控件布局
    [self.lblPriceType mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([self.vCountModificationArr lastObject].mas_bottom).offset(0);
        make.leading.trailing.equalTo(self);
        make.height.offset(30);
    }];
}

#pragma mark Enter with data ...
- (void)setCommodityCategory:(NSString *)commodityCategory {
    _commodityCategory = commodityCategory.copy;
    if (!_commodityCategory || _commodityCategory.isEmpty) {
        // 清空
        [self clearDetailInfo];
        [self clearInfo_check];
        return;
    }
#pragma mark ViewControllerCarSale
    if (self.viewControllerEnum == ViewControllerCarSale) {
        //拿到商品名，去商品档案查询，显示到detailView上（后续创建订单使用）
        // 加载数据
        TCommodityInfoModel * commInfoModel = [self loadCommInfoModelWithCategory:commodityCategory];
        self.commInfoModel = commInfoModel;
        if (!commInfoModel) {
            [self clearDetailInfo];
            [self clearInfo_check];
            return;
        }
        
        // 分发数据
        [self distributeWithCommInfoModel:commInfoModel saleModel:nil];
    }
#pragma mark ViewControllerInventoryCheck
    else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
        //拿到商品名，去商品档案查询，得到商品编号，再去库存查询数量。
        TInventoryModel *inventoryModel = [CSGXCommodityPickerBLL loadInventoryModelWithCommCategory:_commodityCategory];
        self.inventoryModel = inventoryModel;
        if (!inventoryModel) {
            [self clearInfo_check];
            return;
        }
        [self distributeWithInventoryModel:inventoryModel];
        
    }
    
}

- (void)setInventoryModel:(TInventoryModel *)inventoryModel {
    _inventoryModel = inventoryModel;
    
    [self distributeWithInventoryModel:_inventoryModel];
}

///setPreviewSaleModel
- (void)setPreviewSaleModel:(TSaleInfoModel *)previewSaleModel {
    _previewSaleModel = previewSaleModel;
    
    // 加载commInfoModel数据
    TCommodityInfoModel * commInfoModel = [self loadCommInfoModelWithCommNo:previewSaleModel.sCoNo];
    self.commInfoModel = commInfoModel;
    // 设置内部控件数据
    [self distributeWithCommInfoModel:commInfoModel saleModel:previewSaleModel];
    
}

- (void)setSelectedThirdIndex:(NSInteger)selectedThirdIndex {
    _selectedThirdIndex = selectedThirdIndex;
    
    self.isEdit = [self getIsEdit];
    
    self.lastSelectedThirdIndex = selectedThirdIndex;
}

- (void)setSelectedPreviewIndex:(NSInteger)selectedPreviewIndex {
    _selectedPreviewIndex = selectedPreviewIndex;
    self.lastSelectedPreviewIndex = selectedPreviewIndex;
}



#pragma mark - actions
- (void)atextFieldDidBeginEditing:(UITapGestureRecognizer *) tap_txtTime {
    NSLog(@"时间选择视图");
    
    // 弹出时间选择视图
    
}

- (void)btnScanClick:(UIButton *)sender {
    // 扫码
    NSLog(@"scan");
}

#pragma mark - setupUI
- (void)initUI {
    //header View
    UILabel * lblHeader = [UILabel gx_labelWithText:@"商品名称兰陵" fontSize:13 color:kColorWhite];
    [self addSubview:lblHeader];
    lblHeader.backgroundColor = kColorBar;
    lblHeader.textAlignment = NSTextAlignmentLeft;
    
    [lblHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self);
        make.height.mas_offset(30);
    }];
    self.lblHeader = lblHeader;//
    
#pragma mark ViewControllerCarSale 车销销售
    if (self.viewControllerEnum == ViewControllerCarSale) { //车销销售
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDetailInfo) name:@"ClearDetailInfo" object:nil];
        // line2: 销售类型button
        LKGXDropDownListButton * btnSaleType = [LKGXDropDownListButton gx_textButton:@"正常销售" fontSize:13 normalColor:nil selectedColor:nil titleAlignment:NSTextAlignmentLeft];
        [self addSubview:btnSaleType];
        
        [btnSaleType mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self);
            make.top.equalTo(lblHeader.mas_bottom).mas_offset(5);
            make.height.mas_equalTo(30);
        }];
        self.btnSaleType = btnSaleType;
        
        // line3: 库存titleLabel inventoryLabel
        NSString * titleText = @"库存：**箱**瓶";
        UILabel * lblInventory = [UILabel gx_labelWithText:titleText fontSize:13 color:nil];
        [self addSubview:lblInventory];
        //    lblInventory.backgroundColor = [UIColor blueColor];
        
        [lblInventory mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self);
            make.top.equalTo(btnSaleType.mas_bottom).offset(5);
            make.height.mas_offset(30);
        }];
        self.lblInventory = lblInventory;
        
        // line4: （根据传进来的数量循环创建多个‘单位及数量选择button’ btnUnit_Count）
        [self createNumberModificationViews];
        
        // 价格类型label  lblPriceType （标准价、优惠价）
        UILabel * lblPriceType = [UILabel gx_labelWithText:@"正常销售" fontSize:13 color:nil];
        [self addSubview:lblPriceType];
        self.lblPriceType = lblPriceType;
        
        // 根据 countModiViews 的数量修改 lblPriceType的布局
        if (self.vCountModificationArr.count == 0) {
            //
            [lblPriceType mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(lblInventory.mas_bottom).offset(5);
                make.leading.trailing.equalTo(self);
                make.height.offset(30);
            }];
        } else {
            //
            [lblPriceType mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo([self.vCountModificationArr lastObject].mas_bottom).offset(0);
                make.leading.trailing.equalTo(self);
                make.height.offset(30);
            }];
        }
        
        // 单价，根据选择的单位显示本单位对应的单价
        UIView * vPrice = [[UIView alloc] init];
        [self addSubview:vPrice];
        
        [vPrice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lblPriceType.mas_bottom).offset(5);
            make.leading.trailing.equalTo(self);
            make.height.offset(30);
        }];
        
        // 单价文本框
        CSTextField * txtPrice = [CSTextField gx_textFieldWithLineColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] lineWidth:2];
        txtPrice.textColor = [UIColor grayColor];
        txtPrice.font = [UIFont systemFontOfSize:12];
        txtPrice.enabled = NO;
        [vPrice addSubview:txtPrice];
        
        [txtPrice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.leading.equalTo(vPrice);
            make.height.offset(28);
        }];
        
        // 单价单位
        LKGXDropDownListButton * btnPriceUnit = [LKGXDropDownListButton gx_dropDownListWithTextList:@[@"元/箱"] dictionary:@{@"fontSize":@(13), @"normalColor":[UIColor blackColor]}];
        
        [vPrice addSubview:btnPriceUnit];
        
        [btnPriceUnit mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(txtPrice);
            make.width.equalTo(txtPrice).multipliedBy(3.0/2);
            make.leading.equalTo(txtPrice.mas_trailing).offset(0);
            make.trailing.equalTo(vPrice);
        }];
        self.vPrice = vPrice;
        self.txtPrice = txtPrice;
        self.btnPriceUnit = btnPriceUnit;
        
        // 总金额 根据以上信息自动计算总金额
        CSTextField * txtTotalPrice = [CSTextField gx_textFieldWithLineColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] lineWidth:2];
        [self addSubview:txtTotalPrice];
        self.txtTotalPrice = txtTotalPrice;
        
        txtTotalPrice.textColor = [UIColor grayColor];
        txtTotalPrice.font = [UIFont systemFontOfSize:12];
        txtTotalPrice.enabled = NO;
        
        [txtTotalPrice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(btnPriceUnit.mas_bottom).offset(5);
            make.leading.equalTo(self);
            make.trailing.equalTo(self).offset(-30);
            make.height.offset(30);
        }];
        
        UILabel * lblYuan = [UILabel gx_labelWithText:@"元" fontSize:13 color:nil];
        [self addSubview:lblYuan];
        
        [lblYuan mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(txtTotalPrice);
            make.leading.equalTo(txtTotalPrice.mas_trailing).offset(6);
            make.trailing.equalTo(self);
        }];
        
        // 时间（日期）
        CSTextField * txtTime = [CSTextField gx_textFieldWithLineColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] lineWidth:2];
        [self addSubview:txtTime];
        self.txtTime = txtTime;
        
        //  给时间文本框添加轻触手势
        UITapGestureRecognizer * tap_txtTime = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(atextFieldDidBeginEditing:)];
        [txtTime addGestureRecognizer:tap_txtTime];
        tap_txtTime.delegate = self;
        
        [txtTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(txtTotalPrice.mas_bottom).offset(5);
            make.leading.trailing.equalTo(self);
            make.height.offset(30);
        }];
        
        // 备注 备注可以扫码
        CSBaseTextField * txtRemark = [[CSBaseTextField alloc] init];
        [self addSubview:txtRemark];
        self.txtRemark = txtRemark;
        
        //    txtRemark.backgroundColor = [UIColor grayColor];
        
        [txtRemark mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(txtTime.mas_bottom).offset(5);
            make.leading.equalTo(txtTime);
            make.height.offset(30);
        }];
        
        UIButton * btnRemarkScan = [[UIButton alloc] init];
        [btnRemarkScan setImage:[UIImage imageNamed:@"scan"] forState:UIControlStateNormal];
        [self addSubview:btnRemarkScan];
        self.btnRemarkScan = btnRemarkScan;
        
        [btnRemarkScan addTarget:self action:@selector(btnScanClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [btnRemarkScan mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(txtRemark);
            make.leading.equalTo(txtRemark.mas_trailing).offset(2);
            make.trailing.equalTo(self);
            make.width.offset(30);
            make.height.offset(30);
        }];
        
        
    }
#pragma mark ViewControllerInventoryCheck 库存盘点
    else if(self.viewControllerEnum == ViewControllerInventoryCheck) {  //库存盘点
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearInfo_check) name:@"ClearCheckDetailInfo" object:nil];
        // 时间（日期）
        CSTextField * txtTime = [CSTextField gx_textFieldWithLineColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] lineWidth:2];
        [self addSubview:txtTime];
        self.txtTime = txtTime;
        
        //        txtTime.text = [CSGXDateFormatterManager sharedManager].currentDay;
        
        //  给时间文本框添加轻触手势
        UITapGestureRecognizer * tap_txtTime = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(atextFieldDidBeginEditing:)];
        [txtTime addGestureRecognizer:tap_txtTime];
        //        tap_txtTime.delegate = self;
        
        [txtTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lblHeader.mas_bottom).mas_offset(3);
            make.leading.equalTo(self).mas_offset(2);
            make.trailing.equalTo(self).mas_offset(-2);
            make.height.mas_offset(25);
        }];
        [self layoutIfNeeded];
        
        //
        [self createNumberModificationViews];
        
        //参考: 库存
        UILabel *lblInventory = [UILabel gx_labelWithText:@"" fontSize:12 color:nil];
        [self addSubview:lblInventory];
        self.lblInventory = lblInventory;
        
        // 根据 countModiViews 的数量修改 lblPriceType的布局
        if (self.vCountModificationArr.count == 0) {
            //
            [lblInventory mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(txtTime.mas_bottom).offset(5);
                make.leading.trailing.equalTo(self);
                make.height.offset(22);
            }];
        } else {
            //
            [lblInventory mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo([self.vCountModificationArr lastObject].mas_bottom).offset(0);
                make.leading.trailing.equalTo(self);
                make.height.offset(22);
            }];
        }
        
        //
        UIView *vCheck = [[UIView alloc] init];
        [self addSubview:vCheck];
        self.vCheck = vCheck;
        
        [vCheck mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lblInventory.mas_bottom).mas_offset(2);
            make.leading.trailing.equalTo(self).mas_offset(2);
            make.height.mas_offset(45);
        }];
        
        NSArray *checkTitleArr = @[@"盘平", @"盘零", @"未盘"];
        NSMutableArray<UIButton *> *btnCheckList = [NSMutableArray<UIButton *> array];
        
        for (int i = 0; i < checkTitleArr.count; i++) {
            UIButton *button = [UIButton gx_textButton:checkTitleArr[i] fontSize:13 normalColor:nil selectedColor:nil];
            button.tag = i;
            button.backgroundColor = kColorButton;
            [button addTarget:self action:@selector(btnCheckClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [vCheck addSubview:button];
            [btnCheckList addObject:button];
        }
        self.btnCheckList = btnCheckList;
        
        //layout
        [btnCheckList[0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.leading.bottom.equalTo(vCheck).mas_offset(0);
        }];
        [btnCheckList[1] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.top.equalTo(btnCheckList[0]).mas_offset(0);
            make.leading.equalTo(btnCheckList[0].mas_trailing).mas_offset(1);
        }];
        [btnCheckList[2] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.top.equalTo(btnCheckList[0]).mas_offset(0);
            make.leading.equalTo(btnCheckList[1].mas_trailing).mas_offset(1);
            make.trailing.equalTo(vCheck).mas_offset(0);
        }];
        
        //
        UITextView *tvwRemark = [[UITextView alloc] init];
        [self addSubview:tvwRemark];
        self.tvwRemark = tvwRemark;
        
        [tvwRemark mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(vCheck.mas_bottom).mas_offset(5);
            make.leading.equalTo(self).mas_offset(1);
            make.trailing.equalTo(self).mas_offset(-1);
            make.height.mas_offset(100);
        }];
        
        tvwRemark.text = @"产品备注";
        tvwRemark.textColor = [UIColor grayColor];
        tvwRemark.layer.borderColor = [UIColor grayColor].CGColor;
        tvwRemark.layer.borderWidth = 2;
        tvwRemark.layer.shadowOpacity = 0.5;
        tvwRemark.layer.shadowOffset = CGSizeMake(3, 3);
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEdit:) name:UITextViewTextDidBeginEditingNotification object:tvwRemark];
        
    }
    
    
    
} // setupUI end

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}







@end
